package com.wayne.security.config;

import com.wayne.security.service.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;

import javax.annotation.Resource;
import javax.sql.DataSource;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private MyUserDetailsService userService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService);
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    RoleHierarchy roleHierarchy() {
        RoleHierarchyImpl hierarchy = new RoleHierarchyImpl();
        hierarchy.setHierarchy("ROLE_admin > ROLE_user");
        return hierarchy;
    }

    @Autowired
    DataSource dataSource;

    @Bean
    JdbcTokenRepositoryImpl jdbcTokenRepository() {
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
        return jdbcTokenRepository;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 开启权限配置
        http.authorizeRequests()
                .antMatchers("/vc.jpg").permitAll()
                // 所有的请求都要认证之后 才能访问
                //通过自动登录认证后才能访问
                .antMatchers("/rememberme").rememberMe()
                //
                .antMatchers("/admin/**").access("isFullyAuthenticated() and hasRole('admin')")
                .antMatchers("/user/**").access("isFullyAuthenticated() and hasRole('user')")
                .anyRequest().authenticated()
                .and()
                // 开启表单登录配置
                .formLogin()
                // 登录页面地址
                .loginPage("/mylogin.html")
                .usernameParameter("uname")
                .passwordParameter("passwd")
                .loginProcessingUrl("/doLogin")
                .defaultSuccessUrl("/hello")
                .failureForwardUrl("/mylogin.html")
                .permitAll()
                .and()
                .rememberMe()
                //key 默认值是一个 UUID 字符串，这样会带来一个问题，就是如果服务端重启，这个 key 会变，这样就导致之前派发出去的所有 remember-me 自动登录令牌失效，所以，我们可以指定这个 key
                .key("javaboy")
                .tokenRepository(jdbcTokenRepository())
                .and()
                // 禁用 CSRF 防御功能
                .csrf().disable();
    }

}
